package com.hmdp.common.interceptor;

import static com.hmdp.utils.RedisConstants.LOGIN_CODE_KEY;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.common.enums.WebError;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author ortonzhu
 * @ClassName Login 拦截器
 * @Description
 * @date 2024/07/05 11:59
 */
public class ReflashTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public ReflashTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 1.获取请求头中的信息
        String token = request.getHeader("authorization");
        if(StrUtil.isBlank(token)){
            return true;
        }
        // 2.判断是否存在
        String tokenKey = LOGIN_CODE_KEY + token;
        //2.获取用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash(). entries(tokenKey);
        if (userMap.isEmpty()) {
            // 不存在，拦截，状态码：401 未授权
            response.setStatus(WebError.PAGE_DOES_NOT_EXIST.getError());
            return true;
        }

        // map to user
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        // 刷新token
        stringRedisTemplate.expire(tokenKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        UserHolder.removeUser();

    }
}
